from rest_framework import serializers
from .models import User
from django_redis import get_redis_connection
from orders.models import Order


class UserModelSerializer(serializers.ModelSerializer):
    '''用户注册的序列化器'''
    # 声明用户模型类中没有的字段
    sms_code = serializers.CharField(write_only=True, max_length=6, help_text="短信验证码")
    token = serializers.CharField(read_only=True, max_length=1024, help_text="jwt的token字符串")

    # 模型信息
    class Meta:
        model = User
        fields = ['id', 'mobile', 'password', 'sms_code', 'token']
        extra_kwargs = {
            'id': {
                "read_only": True,
            },
            'mobile': {
                'max_length': 15,
                'required': True
            },
            'password': {
                'write_only': True,
                'max_length': 128,
                'required': True
            },
        }

    # 验证数据
    def validate(self, attrs):
        '''校验验证码是否输入正确'''
        mobile = attrs.get('mobile')
        sms_code = attrs.get('sms_code')
        # 连接redis
        redis_conn = get_redis_connection('sms_code')
        # 获取用户的验证码
        real_code = redis_conn.get("sms_%s" % mobile)
        if real_code:
            # 数据库中有验证码才会进行解码，否则会报错
            real_code = real_code.decode()

        if sms_code != real_code:
            raise serializers.ValidationError({'message': '验证码不正确'})

        # 用户验证成功后就删除验证码
        redis_conn.delete("sms_%s" % mobile)

        return attrs

    # 保存数据
    def create(self, validated_data):
        '''重写父类的create方法'''
        # 因为用户库中是没有验证码 sms_code 字段的，所有需要删除掉，否则创建用户会报错
        del validated_data['sms_code']

        # 用户库中有用户名字段不能为空，这边将手机号赋值给用户名
        validated_data['username'] = validated_data['mobile']
        # 调用当前模型序列化器父类的create
        user = super().create(validated_data)

        # 给密码加密
        user.set_password(user.password)
        user.save()

        # 生成jwt的token值，用于记录登录状态
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        # 最终token作为user模型的一个字段返回给客户端
        user.token = jwt_encode_handler(payload)

        return user


class UserOrderModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ["id", "created_time", "order_number", "status", "order_status", "pay_time", "course_list"]


